import {createRouter,createWebHistory} from "vue-router"
import {useRouterStore} from "@/store/router.js";
import {useRouteStore} from "@/store/route.js";
const env = import.meta.env

const routes = [
    {
        path: "/",
        name: "/",
        meta:{
            title:'主页'
        },
        component: () => import("../views/layout/index.vue"),
        redirect: "/index", // 默认跳转
    },

    {
        path: "/login",
        name: 'Login',
        component: () => import("../views/system/login/index.vue")
    },
    {
        path: "/register",
        name: 'Register',
        component: () => import("../views/system/register/index.vue")
    },
    {
        path: "/reset",
        name: 'Reset',
        component: () => import("../views/system/reset/index.vue")
    },
    {
        path: "/404",
        name: 'NotFound',
        component: () => import("@/components/error/404.vue")
    },
    {
        path: "/401",
        name: '401',
        component: () => import("@/components/error/401.vue")
    },{
        path: "/:pathMatch(\b[a-zA-Z0-9]+\b)",
        // path: "/:pathMatch(.*)",
        redirect: "/404",
    }

]


// 3. 创建路由实例并传递 `routes` 配置
// 你可以在这里输入更多的配置，但我们在这里
// 暂时保持简单
const router = createRouter({
    // 4. 内部提供了 history 模式的实现。为了简单起见，我们在这里使用 hash 模式。
    // history: createWebHistory('/xxjszs/'),
    history: createWebHistory(),
    routes, // `routes: routes` 的缩写
})
const whitePath = ['/login','/register','/reset']
router.beforeEach((to, from, next) => {
    const store = useRouterStore()
    const { addDynamicRoutes } = store
    if (whitePath.indexOf(to.path) == -1 && store.routers.length === 0 ) {
        //调用addDynamicRoutes方法，动态路由生成
        // 页面刷新 发送请求，获取路由数据
        //缓存路由 pinia
        addDynamicRoutes().then(()=>{
            next({...to, replace: true}) // hack方法 确保addRoutes已完成
        })
    } else {
        next();
    }
})

function getPageTitle(pageTitle) {
    const localSetting = JSON.parse(window.localStorage.getItem('miaomiao-setting'))
    if (localSetting && localSetting.dynamicTitle && pageTitle) {
        return `${pageTitle} - ${env.VITE_APP_TITLE}`
    }
    return `${env.VITE_APP_TITLE}`
}
router.afterEach((to)=>{
    document.title = getPageTitle(to.meta.title)
    if(to.meta.record){
        const routeStore = useRouteStore()
        let hasOne = routeStore.visitedRoutes.findIndex((val)=>{
            return val.name ===  '主页'
        })
        if(hasOne == -1) {
            routeStore.visitedRoutes.push({path:'/index',name:'主页'});
        }
        let routerHas = routeStore.visitedRoutes.findIndex((val)=>{
            return val.name ===  to.meta.title
        })
        if(routerHas == -1){
            routeStore.visitedRoutes.push({path:to.path,name:to.meta.title});
        }else{
            return
        }
    }else{
        return
    }

})
export default router
